package com.yuwj.chinaa.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.activity.AccountUpdatePaymentPasswordActivity;
import com.yuwj.chinaa.activity.TradeListActivity;
import com.yuwj.chinaa.activity.TradeSuccessActivity;
import com.yuwj.chinaa.base.BaseLazyLoadFragment;
import com.yuwj.chinaa.base.ConstantParam;
import com.yuwj.chinaa.entity.EntityAssetGTEOverview;
import com.yuwj.chinaa.entity.EntityBurseCoinNumber;
import com.yuwj.chinaa.entity.EntityOrderWithTrade;
import com.yuwj.chinaa.entity.EntityTradePriceData;
import com.yuwj.chinaa.entity.EntityTradePriceItem;
import com.yuwj.chinaa.entity.EntityUser;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.DateUtil;
import com.yuwj.chinaa.util.MathUtil;
import com.yuwj.chinaa.util.SharedpreferenceUtil;
import com.yuwj.chinaa.util.ToastUtil;
import com.yuwj.chinaa.util.XAxisValueFormatter;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

//交易碎片
public class FragmentTrade extends BaseLazyLoadFragment {

    EntityUser entityUser;
    int currentTradeType = ConstantParam.TRANSACTION_TYPE_WITH_BUY;//当前交易类型，ConstantParam.TRANSACTION_TYPE_WITH_BUY-买入，1-卖出
    boolean isLoadSuccess;//是否加载成功
    IPresenter presenter;

    EntityBurseCoinNumber entityBurseCoinNumber;
    EntityTradePriceData entityTradePriceData;
    List<EntityTradePriceItem> entityTradePriceItemList;
    double cuurentGtePrice = 0;
    double yesterdayGtePrice = 0;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_trade_list_tip)
    TextView tvTradeListTip;
    @BindView(R.id.tv_current_price)
    TextView tvCurrentPrice;
    @BindView(R.id.tv_zhangf)
    TextView tvZhangf;
    @BindView(R.id.linechart)
    LineChart linechart;
    @BindView(R.id.v_buy_gte)
    View vBuyGte;
    @BindView(R.id.ll_buy_gte)
    LinearLayout llBuyGte;
    @BindView(R.id.v_sell_gte)
    View vSellGte;
    @BindView(R.id.ll_sell_gte)
    LinearLayout llSellGte;
    @BindView(R.id.tv_keyzhzc)
    TextView tvKeyzhzc;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.et_trade_count)
    EditText etTradeCount;
    @BindView(R.id.et_max_limit)
    EditText etMaxLimit;
    @BindView(R.id.ll_max_limit)
    LinearLayout llMaxLimit;
    @BindView(R.id.tv_total_cost)
    TextView tvTotalCost;
    @BindView(R.id.btn_confirm_trade)
    Button btnConfirmTrade;
    Unbinder unbinder;


    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.fragment_trade;
    }

    public static FragmentTrade createInstance() {
        FragmentTrade fragmentTrade = new FragmentTrade();
        Bundle bundle = new Bundle();
        fragmentTrade.setArguments(bundle);
        return fragmentTrade;
    }

    protected void lazyLoad() {
        initParam();
        initView();
        initOperator();
        isLoadSuccess = true;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void initParam() {
        entityUser = SharedpreferenceUtil.getInstance().getUserInfo(context);
        presenter = new PresenterImpl(this);
        entityTradePriceItemList = new ArrayList<>();
    }

    public void initView() {
        updateViewByCurrentTradeType();
        etTradeCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String count = etTradeCount.getText().toString().trim();
                if (TextUtils.isEmpty(count)) {
                    tvTotalCost.setText(0 + "");
                } else {
                    if (TextUtils.isEmpty(tvPrice.getText().toString().trim())) {
                        tvTotalCost.setText(0 + "");
                    } else {
                        tvTotalCost.setText(MathUtil.multiply(tvPrice.getText().toString().trim(), count) + "");
                    }
                }

            }
        });
    }

    boolean isHasSellingOrder = false;

    public void initOperator() {
        JSONObject param = new JSONObject();
        presenter.queryTradePriceData(param.toString());
        updateUserAvailableGTE();

        JSONObject paramWithQueryTransactionOrderList = new JSONObject();
        try {
            paramWithQueryTransactionOrderList.put("pageindex", "1");
            paramWithQueryTransactionOrderList.put("pagesize", "100");
            paramWithQueryTransactionOrderList.put("ordertype", 0 + "");//交易订单类型：0：获取卖出订单，1：获取买入订单（交易中 订单不区分买入和卖出类型）
            paramWithQueryTransactionOrderList.put("orderStatus", "0");//订单状态：0：等待交易，1：交易中 2：交易完成，3：申诉订单
            paramWithQueryTransactionOrderList.put("isAll", "1");//是否查询所有：0：所有交易订单，1：个人交易订单

        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.queryTransactionOrderList(paramWithQueryTransactionOrderList.toString());
    }

    public void updateUserAvailableGTE() {
        JSONObject param = new JSONObject();
        presenter.getUserBurseCoinNumberList(param.toString());
    }

    @OnClick({R.id.ll_buy_gte, R.id.ll_sell_gte, R.id.btn_confirm_trade, R.id.tv_trade_list_tip})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.ll_buy_gte:
                currentTradeType = ConstantParam.TRANSACTION_TYPE_WITH_BUY;
                updateViewByCurrentTradeType();
                break;
            case R.id.ll_sell_gte:
                currentTradeType = ConstantParam.TRANSACTION_TYPE_WITH_SELL;
                updateViewByCurrentTradeType();
                break;
            case R.id.btn_confirm_trade:
                if (TextUtils.isEmpty(etTradeCount.getText().toString())) {
                    ToastUtil.getInstance().shortLength(context, "请输入交易数量");
                    return;
                }
                String price = tvPrice.getText().toString().trim();
                String count = etTradeCount.getText().toString().trim();
                switch (currentTradeType) {
                    case ConstantParam.TRANSACTION_TYPE_WITH_BUY:
                        if (Double.parseDouble(count) < 1) {
                            ToastUtil.getInstance().shortLength(context, "请输入>1的数量");
                            return;
                        }
                        break;
                    case ConstantParam.TRANSACTION_TYPE_WITH_SELL:
                        if (Double.parseDouble(count) < 100 || Double.parseDouble(count) > 10000) {
                            ToastUtil.getInstance().shortLength(context, "请输入100 -- 10000 之间的数量");
                            return;
                        }
                        if (isHasSellingOrder) {
                            ToastUtil.getInstance().shortLength(context, "您还有未卖出的订单,请先处理后再操作");
                            return;
                        }
                        break;
                }

                EntityUser entityUser = SharedpreferenceUtil.getInstance().getUserInfo(context);
                if (entityUser.getIsIdentification() != ConstantParam.GENERAL_AUTH_WITH_SUCCESS) {
                    ToastUtil.getInstance().shortLength(context, "请先实名认证");
                    return;
                }
                if (TextUtils.isEmpty(entityUser.getWithdrawPwd())) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    final AlertDialog dialog = builder.create();
                    dialog.setTitle("提示");
                    dialog.setMessage("您还未设置支付密码,请先前往设置");
                    AlertDialog.OnClickListener alertDialogOnclickListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            switch (i) {
                                case AlertDialog.BUTTON_POSITIVE:
                                    startActivity(AccountUpdatePaymentPasswordActivity.createIntent(context));
                                    dialog.dismiss();
                                    break;
                                case AlertDialog.BUTTON_NEGATIVE:
                                    dialog.dismiss();
                                    break;
                            }
                        }
                    };
                    dialog.setButton(AlertDialog.BUTTON_POSITIVE, "确定", alertDialogOnclickListener);
                    dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", alertDialogOnclickListener);
                    return;
                }
                switch (currentTradeType) {
                    case ConstantParam.TRANSACTION_TYPE_WITH_BUY:
                        if (TextUtils.isEmpty(price)) {
                            ToastUtil.getInstance().shortLength(context, "请输入卖价");
                            return;
                        }
                        if (TextUtils.isEmpty(count)) {
                            ToastUtil.getInstance().shortLength(context, "请输入购买数量");
                            return;
                        }


                        break;
                    case ConstantParam.TRANSACTION_TYPE_WITH_SELL:
                        if (TextUtils.isEmpty(price)) {
                            ToastUtil.getInstance().shortLength(context, "请输入卖价");
                            return;
                        }
                        if (TextUtils.isEmpty(count)) {
                            ToastUtil.getInstance().shortLength(context, "请输入卖出数量");
                            return;
                        }

                        break;
                }
                showInputPayPasswordDialog();


                break;
            case R.id.tv_trade_list_tip:
                startActivity(TradeListActivity.createIntent(context));
                break;
        }
    }

    public void updateViewByCurrentTradeType() {
        switch (currentTradeType) {
            case ConstantParam.TRANSACTION_TYPE_WITH_BUY:
                etTradeCount.setHint("请输入购买数量");
                btnConfirmTrade.setText("确认购买");
                vBuyGte.setVisibility(View.VISIBLE);
                vSellGte.setVisibility(View.INVISIBLE);
                llMaxLimit.setVisibility(View.GONE);
                break;
            case ConstantParam.TRANSACTION_TYPE_WITH_SELL:
                etTradeCount.setHint("请输入卖出数量(100-10000之间)");
                btnConfirmTrade.setText("确认卖出");
                vBuyGte.setVisibility(View.INVISIBLE);
                vSellGte.setVisibility(View.VISIBLE);
                llMaxLimit.setVisibility(View.GONE);
                break;
        }
    }


    //更新价格交易曲线
    public void updatePriceDataTable() {
        tvCurrentPrice.setText(entityTradePriceData.getDayPriceRMB() + "");
        tvZhangf.setText(entityTradePriceData.getIncreasePriceRMB() + "");
        ArrayList<String> xVals = new ArrayList<String>();
        ArrayList<String> yVals = new ArrayList<String>();

        cuurentGtePrice = entityTradePriceData.getDayPriceRMB();
        SharedpreferenceUtil.getInstance().saveTodayPrice(context, (float) cuurentGtePrice);
        tvPrice.setText(cuurentGtePrice + "");
        yesterdayGtePrice = entityTradePriceItemList.get(entityTradePriceItemList.size() - 2).getChinaARMB();
        tvCurrentPrice.setText(cuurentGtePrice + " CNY");
        double zhangf = (cuurentGtePrice - yesterdayGtePrice) / yesterdayGtePrice * 100;
        String str = String.format("%.1f", zhangf);

        tvZhangf.setText(str + "%");

        for (EntityTradePriceItem data : entityTradePriceItemList) {
            String timeStr = data.getChinaAdate();
            timeStr = DateUtil.formatDate(timeStr, "yyyy-MM-dd", "MM-dd");
            String xVal = timeStr + "";
            xVals.add(xVal);
            yVals.add(data.getChinaARMB() + "");
        }

        ArrayList<Entry> valsComp1 = new ArrayList<Entry>();

        for (int i = 0; i < xVals.size(); i++) {
            float y = Float.parseFloat(yVals.get(i));
            BigDecimal b = new BigDecimal(y);
            float y1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();// 表明四舍五入，保留两位小数
            Entry entry = new Entry(i, y1);
            valsComp1.add(entry);
        }


        LineDataSet setComp1 = new LineDataSet(valsComp1, "");
        setComp1.setValues(valsComp1);
        setComp1.setLineWidth(2);
        setComp1.setColor(Color.rgb(213, 96, 164));
        setComp1.setCircleColor(Color.rgb(233, 64, 147));
        setComp1.setValueTextColor(getResources().getColor(R.color.text_color_red));

        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
        dataSets.add(setComp1);


        LineData data = new LineData(dataSets);
        linechart.setData(data);
        XAxis xAxis = linechart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); // 设置X轴的位置
        linechart.getAxisLeft().setEnabled(false);
        linechart.getAxisRight().setDrawGridLines(false);
        linechart.getAxisRight().setDrawAxisLine(false);
        linechart.getAxisRight().setTextColor(getResources().getColor(R.color.text_color_red));
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(xVals.size() - 1);// 设置标签显示的个数

        XAxisValueFormatter xAxisValueFormatter = new XAxisValueFormatter(xVals);
        xAxis.setValueFormatter(xAxisValueFormatter);

        linechart.setDrawBorders(false);
        linechart.getDescription().setEnabled(false);// 设置是否启用描述
        linechart.getLegend().setEnabled(false);// 是否启用图例

        linechart.setTouchEnabled(false);
        linechart.invalidate(); // refresh
    }

    //展示输入支付密码对话框
    public void showInputPayPasswordDialog() {
        NiceDialog niceDialog = null;
        if (niceDialog == null) {
            niceDialog = NiceDialog.init();
            niceDialog.setLayoutId(R.layout.content_input_pay_password);
            niceDialog.setConvertListener(new ViewConvertListener() {
                @Override
                protected void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                    LinearLayout llDismiss = holder.getView(R.id.ll_dismiss);
                    final EditText etpassword = holder.getView(R.id.et_pay_password);
                    TextView tvnext = holder.getView(R.id.tv_buy);

                    llDismiss.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();

                        }
                    });

                    tvnext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (TextUtils.isEmpty(etpassword.getText().toString().trim())) {
                                ToastUtil.getInstance().shortLength(context, "请输入支付密码");
                                return;
                            }

                            dialog.dismiss();
                            showTradeInfoConfirmDialog(etpassword.getText().toString().trim());
                        }
                    });

                }
            });
            niceDialog.setAnimStyle(R.style.popwin_anim_style);
            niceDialog.setDimAmount(0.3f);
            niceDialog.setMargin(50);
            niceDialog.setShowBottom(false);
            niceDialog.setOutCancel(false);

        }
        niceDialog.show(getActivity().getSupportFragmentManager());
    }


    public void showTradeInfoConfirmDialog(final String payPassword) {
        final String priceStr = tvPrice.getText().toString().trim();
        final String countStr = etTradeCount.getText().toString().trim();
//        final String limit=etMaxLimit.getText().toString().trim();
        NiceDialog niceDialog = null;
        if (niceDialog == null) {
            niceDialog = NiceDialog.init();
            niceDialog.setLayoutId(R.layout.content_trade_info_confirm);
            niceDialog.setConvertListener(new ViewConvertListener() {
                @Override
                protected void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                    LinearLayout llDismiss = holder.getView(R.id.ll_dismiss);
                    TextView tvCount = holder.getView(R.id.tv_count);
                    TextView tvPrice = holder.getView(R.id.tv_price);
                    TextView tvTotal = holder.getView(R.id.tv_total);
                    TextView tvXiane = holder.getView(R.id.tv_xiane);
                    TextView tvPriceType = holder.getView(R.id.tv_price_type);
                    if (currentTradeType == ConstantParam.TRANSACTION_TYPE_WITH_BUY) {
                        tvPriceType.setText("买价");
                    } else {
                        tvPriceType.setText("卖价");
                    }

                    tvCount.setText(countStr);
                    tvPrice.setText(priceStr);

                    final double resultDouble = MathUtil.multiply(countStr, priceStr);
                    tvTotal.setText(String.format("%2f", resultDouble));
                    TextView tvConfirm = holder.getView(R.id.tv_confirm);

                    llDismiss.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();

                        }
                    });

                    tvConfirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();

                            JSONObject paramWithBuy = new JSONObject();
                            try {
                                paramWithBuy.put("bicount", countStr + "");
                                paramWithBuy.put("pricermb", priceStr + "");
                                paramWithBuy.put("limitmix", 0 + "");
                                paramWithBuy.put("limitmax", countStr + "");
                                paramWithBuy.put("ordertype", currentTradeType == ConstantParam.TRANSACTION_TYPE_WITH_BUY ? 1 + "" : 0 + "");
                                paramWithBuy.put("paypwd", payPassword + "");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            presenter.gteBuyOrSell(paramWithBuy.toString());
                        }
                    });

                }
            });
            niceDialog.setAnimStyle(R.style.popwin_anim_style);
            niceDialog.setDimAmount(0.3f);
            niceDialog.setMargin(50);
            niceDialog.setShowBottom(false);
            niceDialog.setOutCancel(false);

        }
        niceDialog.show(getActivity().getSupportFragmentManager());
    }


    @Override
    public void onQueryTradePriceDataSuccess(EntityTradePriceData entityTradePriceData) {
        super.onQueryTradePriceDataSuccess(entityTradePriceData);
        this.entityTradePriceData = entityTradePriceData;
        entityTradePriceItemList.clear();
        entityTradePriceItemList.addAll(entityTradePriceData.getModelDayList());
        updatePriceDataTable();
    }

    @Override
    public void onQueryTradePriceDataFail(Exception e) {
        super.onQueryTradePriceDataFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }

    @Override
    public void gteBuyOrSellSuccess(String data) {
        super.gteBuyOrSellSuccess(data);
        startActivity(TradeSuccessActivity.createIntent(context, currentTradeType));
    }

    @Override
    public void gteBuyOrSellFail(Exception e) {
        super.gteBuyOrSellFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());

    }

    public boolean isLoadSuccess() {
        return isLoadSuccess;
    }

    public void setLoadSuccess(boolean loadSuccess) {
        isLoadSuccess = loadSuccess;
    }

    @Override
    public void onAssetGTEOverviewSuccess(EntityAssetGTEOverview entityAssetGTEOverview) {
        tvKeyzhzc.setText(entityAssetGTEOverview.getAvailableAmount() + "GTE");
    }

    @Override
    public void onAssetGTEOverviewFail(Exception e) {
        super.onAssetGTEOverviewFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
        tvKeyzhzc.setText("0GTE");
    }


    @Override
    public void onGetUserBurseCoinNumberListSuccess(EntityBurseCoinNumber entityBurseCoinNumber) {
        super.onGetUserBurseCoinNumberListSuccess(entityBurseCoinNumber);
        this.entityBurseCoinNumber = entityBurseCoinNumber;
        tvKeyzhzc.setText(entityBurseCoinNumber.getAvailableBurseCoinNumber() + " china-A");
    }

    @Override
    public void onGetUserBurseCoinNumberListFail(Exception e) {
        super.onGetUserBurseCoinNumberListFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }

    @Override
    public void queryTransactionOrderListSuccess(List<EntityOrderWithTrade> orderList) {
        super.queryTransactionOrderListSuccess(orderList);
        if (orderList != null && orderList.size() > 0) {
            isHasSellingOrder = true;
        }
    }

    @Override
    public void queryTransactionOrderListFail(Exception e) {
        super.queryTransactionOrderListFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
        isHasSellingOrder = false;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
